package com.shen.library_nettysocket.handler

import io.netty.channel.ChannelInboundHandlerAdapter
import io.netty.channel.ChannelHandlerContext
import com.alibaba.fastjson.JSON
import com.shen.library_nettysocket.netty.NettyTcpClient
import com.shen.library_nettysocket.protobuf.MessageProtobuf
import java.lang.Exception

/**
 * 握手认证消息响应处理handler
 */
class LoginAuthRespHandler(private val imsClient: NettyTcpClient) : ChannelInboundHandlerAdapter() {

    @Throws(Exception::class)
    override fun channelRead(ctx: ChannelHandlerContext, msg: Any?) {

        if(msg !is MessageProtobuf.Msg?) return
        val handshakeRespMsg: MessageProtobuf.Msg? = msg
        if (handshakeRespMsg?.head == null) return

        val handshakeMsg: MessageProtobuf.Msg? = imsClient.handshakeMsg
        if (handshakeMsg?.head == null)
            return
        val handshakeMsgType: Int = handshakeMsg.head.msgType


        when(handshakeMsgType){
            handshakeRespMsg.head.msgType -> {
                println("收到服务端握手响应消息，message=$handshakeRespMsg")
                var status = -1
                try {
                    val jsonObj = JSON.parseObject(handshakeRespMsg.head.extend)
                    status = jsonObj.getIntValue("status")

                } catch (e: Exception) {
                    e.printStackTrace()

                } finally {
                    when(status){
                        1 -> {
                            // 握手成功，马上先「发送一条·心跳消息」，至于「心跳机制·管理」，交由HeartbeatHandler
                            val heartbeatMsg: MessageProtobuf.Msg = imsClient.heartbeatMsg ?: return
                            // 握手成功，检查「消息发送超时·管理器」里是否有「发送超时的消息」，如果有，则全部重发
                            imsClient.msgTimeoutTimerManager?.onResetConnected()
                            println("发送心跳消息：${heartbeatMsg}当前心跳间隔为：${imsClient.heartbeatInterval}ms")
                            imsClient.sendMsg(heartbeatMsg)
                            imsClient.addHeartbeatHandler()                 // 添加「心跳消息」管理handler
                        }
                        else ->  {
                            //imsClient.resetConnect(false);// 握手失败，触发重连
                            // 握手失败且返回了消息一定是服务端认证没通过 所以这里需要关闭客户端
                            imsClient.close()
                        }
                    }

                }
            }
            else -> ctx.fireChannelRead(msg)                // 消息透传
        }
    }

}